<?php
require_once 'bud_mng'.EXT;

class Bud_upload extends Bud_mng {
	protected $model_path = 'm_activity';
	
	function __key_formatting($number){
		if(strlen($number)==1){
			return '0'.$number;
		}else{
			return $number;
		}
	}

		

	function __int_to_month($i)
		{
			switch($i){
				case '1' : 
					return 'januari';
					break;
				case '2' : 
					return 'februari';
					break;
				case '3' : 
					return 'maret';
					break;
				case '4' : 
					return 'april';
					break;
				case '5' : 
					return 'mei';
					break;
				case '6' : 
					return 'juni';
					break;
				case '7' : 
					return 'juli';
					break;
				case '8' : 
					return 'agustus';
					break;
				case '9' : 
					return 'september';
					break;
				case '10' : 
					return 'oktober';
					break;
				case '11' : 
					return 'november';
					break;
				case '12' : 
					return 'desember';
					break;
			}
		}

	function index(){
		if($this->role=='admin'){
			$nav = $this->load->view('bud/navigation/administrator/navigation', '', true);
			$view = 'bud/administrator/upload';
		}else if($this->role=='manager'){
			$nav = $this->load->view('bud/navigation/administrator/nav_manager', '', true);
			$view = 'bud/administrator/upload';
		}else if($this->role=='yayasan'){
			$nav = $this->load->view('bud/navigation/administrator/nav_yayasan', '', true);
			$view = 'bud/administrator/upload';
		}else{
			$nav = '';
			$view = 'bud/illegaluser';
		}

		$data = array(
			 'application' => $prefix,
			 'application_title' => $this->common->get_application_description($prefix),
			 'page' => 'Upload',
			 'navigation' =>  $this->load->view('nav/default', '', true).$nav,
			 'content' => $this->load->view($view,array('menus' => $menus,'base' => $this->config->item('base_url').'system/application/modules/'),true),
		); 

		$this->load->view('bud/layout/default', $data);
	}
	
	

	public function process_import() {
		$import_data = NULL;
		parent::process_import_input($import_data);
		$this->process_import_process($import_data);
		parent::process_import_output($import_data);	
	}

	public function confirm() {
		$hidden = array(
			'versi'=>$versi,
			'import_file'=>$file,
		);
	

		$data = array(
			 'application' => $prefix,
			 'application_title' => $this->common->get_application_description($prefix),
			 'page' => 'Upload',
			 'navigation' =>  $this->load->view('nav/default', '', true).$this->load->view('bud/navigation/administrator/navigation', '', true),
			 'content' => $this->load->view('bud/administrator/confirm_upload',array('hidden'=>$hidden),true),
		); 

		$this->load->view('bud/layout/default', $data);
		
	}


	protected function process_import_process(&$import_data = NULL) {
		$startline = 6; //Startime reading line
		$count = 0; // Sucess timed
		$exist = 0;
		$this->db->trans_start();
		$versi = strtolower($_POST['versi']);
		
		
		if (is_null($import_data)) $import_data = array();
		
		$derr = array();
		if(ereg('^[v][0-9]{2}[/][0-9]{4}$',$versi)){
			$qry = $this->db->query("select * from `bud_m_version` where `key`='$versi'");
			if (!($qry->num_rows() > 0))
			{
			   $execute =  $this->db->query("INSERT INTO `bud_m_version`(`key`) VALUES ('$versi')");
			}

			$qry=$this->db->query("SELECT(EXISTS(SELECT * FROM `bud_m_d_activity` WHERE `key_bud_m_version`='".$versi."')) as 'status'");
			$row = $qry->row_array();
			$exist = $row['status'];	
			if(!$exist){
				if(eregi('.csv',substr($_FILES['import_file']['name'],-4))){
					if (isset($import_data['import_file'])) {
						if (($handle = fopen($import_data['import_file'], 'r')) !== FALSE) {
							
							$error = false;
							$row = fgets($handle);
							if(count(explode("#",$row))>1 ){
								$delimiter =  "#";
							}else if(count(explode(";",$row))>1 ) {
								$delimiter =  ";";
							}else{
								$delimiter =  ",";
							}
							
							rewind ($handle);
							$message = "";
							while (!feof($handle)) {
								$temp_bulan = array();
								$insert_data = array();
								

								//$row = fgets($handle);
								$row = explode($delimiter,fgets($handle));
								$i+=1;
								
								if($i>=$startline && count(array_unique($row))>2 ){  // Avoid the empty line and header of csv document
									$pemakaian = 0;
									$this->db->trans_start();

									$exist = TRUE;
									//----validate fk
										//---program
									$query = $this->db->query("select * from `bud_m_program` where `key`='".$row[0].'.'.$this->__key_formatting($row[1]).'.'.$this->__key_formatting($row[2])."'");

									if (!($query->num_rows() > 0))
									{
									   $message .= "<BR>Aktivitas ID : ".$row[0].'.'.$this->__key_formatting($row[1]).'.'.$this->__key_formatting($row[2]).".".$this->__key_formatting($row[3])." gagal di tambahkan<BR>&nbsp;&nbsp;&nbsp;->Program dengan ID : ".$row[0].'.'.$this->__key_formatting($row[1]).'.'.$this->__key_formatting($row[2])." tidak terdaftar dalam database, tambahkan dahulu ke tabel program";
									  
									   $exist = FALSE;
									} 

										//---act yayasan
									$query = $this->db->query("select * from `bud_m_yayasan_activity` where `key`='".$row[26]."'");

									if (!($query->num_rows() > 0))
									{
									 
									   $message .= "<BR>Aktivitas ID : ".$row[0].'.'.$this->__key_formatting($row[1]).'.'.$this->__key_formatting($row[2]).".".$this->__key_formatting($row[3])." gagal di tambahkan<BR>&nbsp;&nbsp;&nbsp;->Aktivitas yayasan dengan ID : ".$row[26]." tidak terdaftar dalam database, tambahkan dahulu ke tabel aktivitas yayasan";
									  
									   $exist = FALSE;
									} 
										//---sumber
									$query = $this->db->query("select * from `bud_r_sumber` where `key`='".$row[27]."'");

									if (!($query->num_rows() > 0))
									{
									 
									   $message .= "<BR>Aktivitas ID : ".$row[0].'.'.$this->__key_formatting($row[1]).'.'.$this->__key_formatting($row[2]).".".$this->__key_formatting($row[3])." gagal di tambahkan<BR>&nbsp;&nbsp;&nbsp;->Sumber dengan ID : ".$row[27]." tidak terdaftar dalam database, tambahkan dahulu ke tabel sumber";
									  
									   $exist = FALSE;
									} 

										//---unit
									$query = $this->db->query("select * from `bud_r_unit` where `key`='".trim($row[28])."'");

									if (!($query->num_rows() > 0))
									{
									 
									   $message .= "<BR>Aktivitas ID : ".$row[0].'.'.$this->__key_formatting($row[1]).'.'.$this->__key_formatting($row[2]).".".$this->__key_formatting($row[3])." gagal di tambahkan<BR>&nbsp;&nbsp;&nbsp;->Unit dengan ID : ".trim($row[28])." tidak terdaftar dalam database, tambahkan dahulu ke tabel unit";
									  
									   $exist = FALSE;
									} 

									//-----------------
									if($exist==FALSE){
										$err_count++;
										continue;
									}

									
									for($j=6;$j<=17;$j++){ // 6 until 17 is month field
										$pemakaian += $row[$j];
									}
									$perbulan = $pemakaian!=0?$row[18]/$pemakaian:0;

								
									for($j=6;$j<=17;$j++){
										$temp_bulan[$this->__int_to_month($j-5)] = $row[$j]!=false ? $perbulan:0; //Assign ke masing2 bulan 
									}
							
									
									$insert_data["key"] = $row[0].'.'.$this->__key_formatting($row[1]).'.'.$this->__key_formatting($row[2]).'.'.$this->__key_formatting($row[3]);
									$insert_data["name_activity"] = $row[4];
									$insert_data["desc_activity"] = $row[5];
									$insert_data["total"] = $row[18];
									$insert_data["gaji_honor"] = $row[19];
									$insert_data["barang_tak_habis"] = $row[20];
									$insert_data["barang_habis"] = $row[21];
									$insert_data["perjalanan"] = $row[22];
									$insert_data["jasa_honor_ext"] = $row[23];
									$insert_data["volume"] = $row[24];
									$insert_data["operational"] = $row[25];
									$insert_data["key_bud_m_yayasan_activity"] = $row[26];
									$insert_data["key_bud_r_sumber"] = $row[27];
									$insert_data["key_bud_r_unit"] = trim($row[28]);  //Clean the bof from \r and \n
									$insert_data["key_bud_m_program"] = $row[0].'.'.$this->__key_formatting($row[1]).'.'.$this->__key_formatting($row[2]);
									$insert_data["key_bud_m_version"] = $_POST['versi'];
									
									$insert_data = array_merge($insert_data,$temp_bulan);
								
									$this->common->who_am_i($insert_data, true, 'crea');
									$status = $this->db->insert('bud_m_d_activity', $insert_data); //$this->model->add($insert_data);	
									
									if ($status === FALSE) {
										$error = true;
										break;
									}
									$count++;
									
								}
							}
							$this->db->trans_complete();
						
							if (($error) || ($this->db->trans_status() === FALSE)) {
								$import_data['error'] = true;
								$this->db->trans_rollback();					
							} else {
								$import_data['error'] = false;
								$import_data['n_rows'] = $count;
								
								$import_data['additional_info'] = $err_count?"<hr><BR> $err_count gagal di tambahkan<BR>$message":"";
								
								$this->db->trans_commit();
							}
							$this->db->trans_off();
							fclose($handle);
						}			
					}
				}else{
					$this->common->flash_message('File tidak didukung, format file harus .csv<hr>Save as file .xls ke format .csv(comma delimiter)',1);
					redirect('bud/bud_upload');
				}
			}else{
				$this->common->flash_message("Budget dengan versi $versi sudah terdaftar dalam database, gunakan nama versi yang berbeda",1);
				redirect('bud/bud_upload');
			}
		}else{
			$this->common->flash_message('Perhatikan format penamaan versi yang benar',1);
			redirect('bud/bud_upload');
		}
	}
}
?>